﻿using ETModel;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;

public class Context : MonoBehaviour,CameraGesture.IGestureHandler {
    [SerializeField] CameraGesture cameraCtrl;
    void Start()
    {
        DontDestroyOnLoad(gameObject);
        //OnStart();
        cameraCtrl.Enter(this);
    }

    private async void OnStart()
    {
        try
        {
            SynchronizationContext.SetSynchronizationContext(OneThreadSynchronizationContext.Instance);

            Game.EventSystem.Add(DLLType.Model, typeof(Init).Assembly);

            Game.Scene.AddComponent<GlobalConfigComponent>();
            Game.Scene.AddComponent<NetOuterComponent>();
            Game.Scene.AddComponent<ResourcesComponent>();
            Game.Scene.AddComponent<PlayerComponent>();
            Game.Scene.AddComponent<UnitComponent>();
            Game.Scene.AddComponent<UIComponent>();

            // 下载ab包
            await BundleHelper.DownloadBundle();

            Game.Hotfix.LoadHotfixAssembly();

            // 加载配置
            Game.Scene.GetComponent<ResourcesComponent>().LoadBundle("config.unity3d");
            Game.Scene.AddComponent<ConfigComponent>();
            Game.Scene.GetComponent<ResourcesComponent>().UnloadBundle("config.unity3d");
            Game.Scene.AddComponent<OpcodeTypeComponent>();
            Game.Scene.AddComponent<MessageDispatcherComponent>();

            Game.Hotfix.GotoHotfix();

            Game.EventSystem.Run(EventIdType.TestHotfixSubscribMonoEvent, "TestHotfixSubscribMonoEvent");
            Log.Info("Game Start ====>Context OK<====");
        }
        catch (System.Exception e)
        {
            Log.Error(e);
        }
    }

    void Update()
    {
        cameraCtrl.OnUpdate();
        OneThreadSynchronizationContext.Instance.Update();
        Game.Hotfix.Update?.Invoke();
        Game.EventSystem.Update();
    }

    private void LateUpdate()
    {
        Game.Hotfix.LateUpdate?.Invoke();
        Game.EventSystem.LateUpdate();
    }

    private void OnApplicationQuit()
    {
        Game.Hotfix.OnApplicationQuit?.Invoke();
        Game.Close();
    }

    public void OnEnter()
    {

    }

    public void OnExit()
    {

    }

    public bool IsCameraOn()
    {
        return true;
    }

    public void OnPointDown(Vector2 screenPos, Vector3 worldPos)
    {

    }

    public void OnPointUp(Vector2 screenPos, Vector3 worldPos)
    {

    }

    public void OnTap(Vector2 screenPos, Vector3 worldPos)
    {

    }

    public void OnZoom(int zoomLevel)
    {

    }

    public bool OnDrag(Vector2 screenPos)
    {
        return false;
    }
}
